﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using com.pro2e.console.core.hibernate;
using NHibernate;

/// <summary>
/// ErrorModule 的摘要描述
/// </summary>
/// 
namespace com.pro2e.web.exception
{
    public class ErrorModule : IHttpModule
    {
        log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        //private static readonly string ERROR_FILE = "errorFile";

        public ErrorModule()
        {

        }
        #region Fields and Properties



        #endregion

        #region IHttpModule Members

        public void Init(HttpApplication application)
        {
            application.Error += new EventHandler(application_Error);

        }

        public void Dispose() { }

        #endregion

        public void application_Error(object sender, EventArgs e)
        {
            HttpContext ctx = HttpContext.Current;
            //記錄Log
            log.Error(ctx.Error);
            
            object a = ctx.Trace;
            //恢復交易
            DoRollBack();

            //錯誤處理
            DoExceptionHandler();

        }

        private void DoExceptionHandler()
        {
            HttpContext ctx = HttpContext.Current;

            object exception = ctx.Server.GetLastError();

            if (exception is HttpRequestValidationException)
            {
                //"因安全性要求不允許非法字元";
                ctx.Response.Redirect("~/common/error/security.aspx",false);
                return;
            }
                //TODO:捉viewstate error
            else if (exception is ViewStateException) 
            {
                //重新登入
                ctx.Response.Redirect("~/admin/Login/Login.aspx", false); 
                return;
            }
            else
            {
                //ctx.Response.Redirect("~/common/error/index.aspx",false);     
                return;
            }
        }

        private void DoRollBack()
        {
            ISession session = NHibernateSessionManager.Instance.GetSession();
            session.Transaction.Rollback();

        }        

    }
}